package com.hoyue.servlet;

import com.hoyue.bean.WorkDisplay;
import com.hoyue.service.WorkDisplayService;
import com.hoyue.utils.Page;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/WorkServlet")
public class WorkDisplayServlet extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("method");//获取方法名
		if (name == null || name.isEmpty()) {
			throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
		}
		Class c = this.getClass();//获得当前类的Class对象
		Method method = null;
		try {
			//获得Method对象
			method = getClass().getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("没有找到" + name + "方法，请检查该方法是否存在");
		}

		try {
			method.invoke(this, request, response);//反射调用方法
		} catch (Exception e) {
			System.out.println("你调用的方法" + name + ",内部发生了异常");
			throw new RuntimeException(e);
		}
	}

	WorkDisplayService workDisplayService = new WorkDisplayService();

	protected void adminGetWorks(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		double randomNum = Math.random();
		request.setAttribute("randomNum", randomNum);
		// 获取页码
		String page1 = request.getParameter("page");

		if(page1 == null || "".equals(page1)) {
			page1 = "1";
		}

		int page = Integer.parseInt(page1);

		Page<WorkDisplay> works = workDisplayService.getPage(page);

		request.setAttribute("works",works);

		request.getRequestDispatcher("/WEB-INF/admin/achievement.jsp").forward(request, response);
	}

	protected void addWorkDisplay(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WorkDisplay workDisplay = new WorkDisplay();

		Map<String, Object> map = new HashMap<>();

		DiskFileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload sfu = new ServletFileUpload(factory);

		StringBuffer category = new StringBuffer("");
		int flag = 0;

		try {
			List<FileItem> items = sfu.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String fileName = item.getFieldName();
					String fileValue = item.getString("UTF-8");
					if(fileName.equals("category")) {
						if(flag == 0) {
							category.append(fileValue);
							flag = 1;
						} else {
							category.append(" " + fileValue);
						}
						continue;
					}
					map.put(fileName, fileValue);
				} else {

					String name = System.currentTimeMillis() + ".jpg";
					String photoFolder = this.getServletContext().getRealPath("page/images/workdisplay");

					InputStream inputStream = item.getInputStream();

					OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);

					IOUtils.copy(inputStream, outputStream);

					inputStream.close();
					outputStream.close();
					item.delete();

					map.put("picPath", "page/images/workdisplay/" + name);
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		try {
			map.put("category",category);
			BeanUtils.populate(workDisplay,map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		workDisplayService.addWorkDisplay(workDisplay);
		response.sendRedirect(request.getContextPath() + "/WorkServlet?method=adminGetWorks");
	}

	protected void deleteInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int id = Integer.parseInt(request.getParameter("id"));
		String picPath = request.getParameter("picPath");
		String address = this.getServletContext().getRealPath(picPath);

		File file = new File(address);
		if(file.exists()) {
			file.delete();
		}
		workDisplayService.deleteWorkDisplay(id);

		request.getRequestDispatcher(request.getContextPath() + "/WorkServlet?method=adminGetWorks").forward(request, response);
	}

	protected void updateWork(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		WorkDisplay workDisplay = new WorkDisplay();
		workDisplay.setId(id);

		Map<String, Object> map = new HashMap<>();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);

		StringBuffer category = new StringBuffer("");
		int flag = 0;

		try {
			List<FileItem> items = sfu.parseRequest(request);

			for (FileItem item : items) {
				if (item.isFormField()) {
					String fileName = item.getFieldName();
					String fileValue = item.getString("UTF-8");
					if(fileName.equals("category")) {
						if(flag == 0) {
							category.append(fileValue);
							flag = 1;
						} else {
							category.append(" " + fileValue);
						}
						continue;
					}
					map.put(fileName, fileValue);
				} else {
					String address = workDisplayService.getPicPathById(id);
					String name = address.substring(address.lastIndexOf("/") + 1);

					if(item.getName().equals("")) {
						map.put("picPath",address);
						continue;
					}

					String photoFolder = this.getServletContext().getRealPath("page/images/workdisplay");

					InputStream inputStream = item.getInputStream();
					OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);

					IOUtils.copy(inputStream,outputStream);

					inputStream.close();
					outputStream.close();
					item.delete();

					map.put("picPath",address);
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		try {
			map.put("category",category);
			BeanUtils.populate(workDisplay, map);
		} catch (Exception  e) {
			e.printStackTrace();
		}
		workDisplayService.update(workDisplay);

		response.sendRedirect(request.getContextPath() + "/WorkServlet?method=adminGetWorks");
	}

}
